#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int latestTimeCatchTheBus(vector<int>& buses, vector<int>& pass, int capacity) {
    sort(buses.begin(), buses.end());
    sort(pass.begin(), pass.end());

    int pos = 0, k = 0;
    for (int arrive : buses)
    {
        k = capacity;
        while (k > 0 && pos < pass.size() && pass[pos] <= arrive)
        {
            k--;
            pos++;
        }
    }

    pos--;
    int last = k > 0 ? buses.back() : pass[pos];
    while (pos >= 0 && pass[pos] == last)
    {
        pos--;
        last--;
    }
    return last;
}

int main()
{
    vector<int> v1 = { 3 }, v2 = { 2 };
    latestTimeCatchTheBus(v1, v2, 2);
    return 0;
}